// pages/cutprice/bargaindetail.js
import Router from '../../utils/router';
import base from '../../config/base.js';
import service from '../../services/cutprice';
import ext from '../../utils/login';
import Record from '../../utils/page-record.js';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    link: 'https://kpxd.zhengdianhaohuo.com/h5/#/active/win3_931',
    bargain_bgc: base.static + 'bargain/bargain-bgc.png',
    bargain_guang: base.static + 'bargain/guang.png',
    bargain_fu: base.static + 'bargain/kanjia22.gif',
    cutdown_money: base.static + 'bargain/bitmap.png',
    baodao_img: base.static + 'bargain/baodao-img.png',
    baodao1_img: base.static + 'bargain/baodao1-img.png',
    closebaodao_img: base.static + 'bargain/closebaodao.png',
    notbargain_img: base.static + 'bargain/not-bargain.png',
    bargain_other_img: base.static + 'bargain/bargain-other.png',
    noshare_img: base.static + 'bargain/noshare.png',
    sanjiao_img: base.static + 'conch/sanjiao.png',
    over_img: base.static + 'bargain/overimg.png',
    qiangguang_img: base.static + 'bargain/qiangguang.png',
    yifenna_img: base.static + 'bargain/yifenna.png',
    icon_no_avater: base.static + '/free/head.png',
    avatar:'',
    hottodyList:[],//热销爆款
    scrolltop:'',//监听页面高度
    store_id: '',
    user_id: '',
    pages: 1,
    per_page: 10,
    sharepath:'',//分享微信列表图片
    endbloon: false,
    loading_flag:true,
    nomore: false,
    mask_flag:false,//蒙层
    baodaomask:false,//宝刀弹框
    bnorid: '',//砍价订单id
    bargain_list:'',//砍价订单详情
    self_avatar: '',//当前店主头像
    last_cuts:'',//剩余砍价次数
    all_cuts:'',//总共砍价次数
    is_self:'',//是否是本人访问
    bargain_code:'',//砍价状态
    bargainfriendList: [],//砍价排行榜列表
    bargain_pages: 1,
    bargain_endbloon:false,
    bargain_loading_flag: true,
    share_getbaodao:false,//自己砍掉价格弹框
    share_getbaodao_box:false,
    baodaobox_show: false,//宝刀砍掉价格弹框
    //baodao_flag:false,分享即送极速宝刀弹框
    swiperList: [],
    cutmoney:'',//砍价金额
    mask_other:false,
    topay_mask:false,//待支付弹框
    topay_num: 1,
    hours: null, //倒计时小时
    minutes: '', //倒计时分钟
    seconds: '', //倒计时秒
    loser_flag: false,//砍价失败弹框
    unclaimed_flag: false,//砍价成功立即领取弹框
    orderstatus: false,
    share:false,
    getbaodao_typenum: 1,//点击分享到群得极速宝刀
    getfriend_typenum: 1,//点击邀请好友砍一刀
    share_url: '',//商品分享图片
    otherPeople_flag:false,
    otherPeople_friend: 1,
    noauthorize: null,
    timeshow: 1,
    fshow: 0,
    transmit1: {
      style: ' width: 320rpx;height: 80rpx;position: absolute;left:0;top:0;z-index:20;background: transparent;',
      value: ''
    },
    transmit2: {
      style: 'width: 534rpx;height: 88rpx;background: #FE3F3E;color: #fff;text-align: center;line-height: 88rpx;font-size: 32rpx;border-radius: 44rpx;letter-spacing: 1.5rpx;margin: 0 auto;margin-top: 40rpx;',
      value: '帮Ta砍一刀'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user_info = wx.getStorageSync('user_info');
    let list = wx.getStorageSync('activity').share_activity;
    if (list == 1) {
      this.setData({
        fshow: 1
      })
    } else {
      this.setData({
        fshow: 0
      })
    }
    this.setData({
      user_id: user_info.id,
      store_id: options.store_id,
      bnorid: options.bnorid,
    })
    this.hotgoods(this.data.pages)//热销爆款
    this.getbargainfriendList(this.data.bargain_pages)//砍价榜
    this.getCycleMsg();//一份拿轮播
    this.getbargainorderdetail(options.bnorid)//砍价详情    
    wx.hideShareMenu();    
  },
  //授权
  onGotUserInfo: function (e) {
    let that = this;
    let d = e.detail;
    if (d.errMsg == 'getUserInfo:ok') {
      ext.getUserInfo(d, b => {
        if (b) {
          if (that.data.otherPeople_flag){ 

          }else {
            that.setData({
              mask_flag: false,              
            })
          }
          that.setData({
            noauthorize: 1,
          })
        }
      });
    }
  }, 
  //关闭分享送宝刀弹框
  closeBaoDao(e){
    //let crid= e.currentTarget.dataset.crid;
    this.setData({
      baodao_flag: false,
    })
  },
  //砍价订单详情
  getbargainorderdetail(bnorid){
    let that = this;
    let param = {
      bnorid: bnorid
    }
    service.getbargainorderdetail(param,function(res){
       if(res && res.code == 1){
         let bargain_list = res.data.orders;
         let progress_width = Math.ceil(bargain_list.have_bargain_money / bargain_list.goods_list_money * 622);
         bargain_list.progress_width = progress_width;
         bargain_list.self_avatar = res.data.self_avatar;
         bargain_list.user_nickname = res.data.user_nickname;
         //判断有没有授权
         let user_info = wx.getStorageSync("user_info");
         if (user_info.info_authorize == 1 && res.data.is_self == 0) {
           that.setData({
             noauthorize: 1,
           })
         } else if (user_info.info_authorize != 1 && res.data.is_self == 0){
           that.setData({
             noauthorize: 2,
             mask_flag: true 
           })
         }
         //判断是否是新开砍价单，宝刀弹框是否显示
         if (bargain_list.have_bargain_money <= '0.00' && res.data.is_self == 1 && res.data.code ==1){
           that.setData({
             //baodao_flag: true,
             mask_flag: true,
             share_getbaodao_box: true,
             share_getbaodao: true,
           })
            that.bargainFriend()           
         }
         
         //判断是否有未支付和待领取订单
         if ((bargain_list.order_status == 2 || bargain_list.order_status == 3) && res.data.is_self == 1){
           progress_width = 622;
           that.setData({
             mask_flag: true,
             orderstatus: true,
           })
         }
         //判断好友通过砍价分享进来是否显示帮砍弹框
         if (res.data.is_self == 0 && res.data.orders.order_status == 1 && res.data.code == 1) {
           that.setData({
             otherPeople_flag: true,
             mask_flag: true,
           })
         }
         //倒计时结束时显示砍价成功与否弹框
         if (res.data.is_self == 1 && (res.data.orders.order_status == 5 || bargain_list.order_status == 3) && that.data.timeshow == 2){
           that.setData({
             mask_flag: true, 
             orderstatus: true,            
           })
         }
         wx.stopPullDownRefresh();         
         that.setData({
           bargain_list: bargain_list,
           self_avatar: res.data.self_avatar,
           user_nickname: res.data.user_nickname,
           last_cuts: res.data.last_cuts,//剩余砍价次数
           all_cuts: res.data.all_cuts,//砍价总次数
           is_self: res.data.is_self,//是否是自己访问
           bargain_code: res.data.code,
           bngsid: res.data.orders.bngsid,
           orid: res.data.orders.orid,
           share_url: res.data.orders.share_url,//商品分享图片
         })         
         setTimeout(()=>{
           that.setData({
             timeshow: 1                        
           })
         },1500)
         if (that.goodstimer){
           clearTimeout(that.goodstimer);           
         }
         that.getremainingtime(bargain_list.end_time)//倒计时
       }
    })
  },
  //获取砍价排行榜
  getbargainfriendList(page){
    let that = this;
    let param = {
      page: page,
      offset: 30,
      bnorid: that.data.bnorid
    }
    service.getbargainfriendList(param,function(res){
      if(res && res.code ==1){
        let bargainfriendList = that.data.bargainfriendList.concat(res.data);
        that.setData({
          bargain_pages: page+1,
          bargainfriendList: bargainfriendList,
          bargain_endbloon: true,
        })
        wx.stopPullDownRefresh();
        if (bargainfriendList.length == res.count) {
          that.setData({
            bargain_loading_flag: false,
          })
        }
      }
    })
  },
  //砍价榜触底事件
  getkanjianbang(){
    if (this.data.bargain_endbloon && this.data.bargain_loading_flag){
      this.setData({
        bargain_endbloon: false
      })
      this.getbargainfriendList(this.data.bargain_pages)      
    }
  },
  //热销爆款
  hotgoods(page) {
    let that = this;
    let params = {
      page: page,
      per_page: 20
    };
    service.customerRecommend(params, function (res) {
      if (res && res.code == 200) {
        let hottodyList = that.data.hottodyList.concat(res.data.recommend);
        that.setData({
          pages: page + 1,
          hottodyList: hottodyList,
          endbloon: true,
        })
        wx.stopPullDownRefresh();
        if (hottodyList.length == res.data.count) {
          that.setData({
            loading_flag:false,
            nomore: true
          })
        }
      }
    })
  },
  

  //1分拿轮播
  getCycleMsg(){
    let that = this;
    service.getCycleMsg({},function(res){
      if(res && res.code == 200){
        wx.stopPullDownRefresh();        
        that.setData({
          swiperList: res.data.dataList
        })
      }
    })
  },
  //阻止swipeer手滑
  stopTouchMove: function () {
    return false
  },
  
  // 点击好友砍价和极速宝刀砍价
  bargainFriend(crid){
    let that = this;
    let param = '';
    if (crid){//宝刀砍价参数
      param = {
        bnorid: that.data.bnorid,
        crid:crid
      }
    }else{//自己和好友砍价参数
      param = {
        bnorid: that.data.bnorid,
      }
    }
    service.bargainFriend(param,function(res){
      if(res && res.code == 1){
        that.setData({
          cutmoney: res.data.cutMoney,
          bargainfriendList: [],
        })
        that.getbargainorderdetail(that.data.bnorid);                  
        that.getbargainfriendList(1);              
      }else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //帮我砍一刀
  helpbargainHandle(){ 
    this.setData({
      mask_other:true,
      mask_flag:false,
      otherPeople_friend: 2  ,
      bargainFriend_flag: 1    
    })
    this.bargainFriend();
    let p = getCurrentPages().pop();
    Record.clickButton(p, 'help_bargain');
  },
  //关闭他人帮砍价弹框
  closemaskOther(){
    this.setData({
      mask_other: false,      
    })
  },
  //点击送极速宝刀
  getBaoDaoHandle(){
    let that = this;
    that.setData({
      baodaobox_show: true,
      mask_other: true,
      getbaodao_typenum: 1,
      share_getbaodao_box: false,
      share_getbaodao: false,
      mask_flag:false
    })
    let crid = '0';
    that.bargainFriend(crid);
  },
  //查看页面规则
  goRule() {
    //Router.go('rule'); 小程序规则页面
    var link = encodeURIComponent(this.data.link);
    if (link) {
      Router.go('web', `url=${link}`, 'navigateTo');
    }
  },
  // 倒计时
  goodstimer: null,
  getremainingtime(time) {
    let that = this;
    that.goodstimer = setTimeout(function () {
      if (time == 0) {
        that.setData({
          hours: '00',
          minutes: '00',
          seconds: '00',
          timeshow: 2,
        });
        clearTimeout(that.goodstimer);
        //倒计时等于0时刷新订单详情显示砍价成功与否弹框
       that.getbargainorderdetail(that.data.bnorid)
      } else {
        time = time - 1;
        that.setData({
          hours: parseInt(time / 60 / 60) >= 10 ? parseInt(time / 60 / 60) : '0' + parseInt(time / 60 / 60),
          minutes: parseInt(time / 60 % 60) >= 10 ? parseInt(time / 60 % 60) : '0' + parseInt(time / 60 % 60),
          seconds: parseInt(time % 60) >= 10 ? parseInt(time % 60) : '0' + parseInt(time % 60),
        });
      }
      if (that.goodstimer) {
        that.getremainingtime(time)
      }
    }, 1000)
  },
  //重来一次
  gocutpricelist(){
    this.setData({
      mask_flag:false,
      orderstatus:false,
    })
    Router.go('cutpricelist', '','redirectTo')
  },
  //去支付订单详情页
  topayHandle(){
    this.setData({
      mask_flag: false,
      orderstatus:false,
    })
    Router.go('orderDetail', `orid=${this.data.orid}`);
  },
  //去提交订单页
  gojielong(){
    this.setData({
      mask_flag: false,
      orderstatus:false,
    })
    let difference = this.data.bargain_list.total_money;
    let bnorid = this.data.bnorid;
    let bngsid = this.data.bngsid;
    let types = 2;
    let store_id = this.data.store_id;
    if (this.data.timeshow == 1){
      Router.go('jielong', `difference=${difference}&bnorid=${bnorid}&types=${types}&store_id=${store_id}&bngsid=${bngsid}`);          
    }
    let p = getCurrentPages().pop();
    Record.clickButton(p, 'go_submit_order');
  }, 
  //点击页面中邀请好友显示canvas组件
  // getEvent(e){
  //   let that = this;
  //   that.setData({
  //     share: true,
  //   })  
  // },
  //查看商品
  godetailHandle(){
    let bngsid = this.data.bngsid;
    Router.go('details', `bngsid=${bngsid}`)
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.setData({
        scrolltop: e.scrollTop
      })
    }, 500);
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    //通过分享微信好友列表回来后显示宝刀砍价弹框 
    // if (that.data.getbaodao_typenum == 2){      
    //   that.setData({
    //     baodaobox_show: true , 
    //     mask_other:true,
    //     getbaodao_typenum: 1,
    //   })
      
    //   let crid = '0';
    //   that.bargainFriend(crid);
    // } 
    if (that.data.getfriend_typenum == 2){
      //点击宝刀砍价弹框的分享微信刷新砍价榜
      
      that.getbargainfriendList(that.data.bargain_pages)      
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    }; 
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      loading_flag:true,
      hottodyList: [],//热销爆款
      pages: 1,
      bargainfriendList: [],//砍价榜
      bargain_pages:1,
      bargain_loading_flag:true,
      bargain_list: '',//砍价订单详情
      swiperList:[]
    })
    this.getbargainorderdetail(this.data.bnorid);//砍价订单详情
    this.getbargainfriendList(1)//砍价榜
    this.hotgoods(1)//热销爆款
    this.getCycleMsg();//一份拿轮播
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.endbloon && this.data.loading_flag){
      this.setData({
        endbloon:false
      })
      this.hotgoods(this.data.pages)
    }
  },
   
  /**
    * 用户点击右上角分享
    */
  onShareAppMessage: function (e) {
    let that = this;  
    if (e.target.dataset.getfriend) {
      that.setData({
        getfriend_typenum: 2,
        baodaoox_show:false
      })
    }
    let p = getCurrentPages().pop();
    Record.clickButton(p, 'Invitation_bargain');
    let bnorid = that.data.bnorid;
    let store_id = that.data.store_id;
    let share_id = wx.getStorageSync('user_info').id;
    let title_arr = ['有空的话，帮我砍个价呗', '这不是演习！留给我的时间不多了！就差你一刀啦~', '朋友一声吼，1分好物就到手', '砍砍砍，砍到1分不是梦', '没有套路，砍多少减多少', '不玩虚的，砍多少减多少', '莫愁前路无知己，1分商品等着你', '随手砍一刀，一分也是爱','临门一脚，最后一刀，亲们：求砍！'];
    let index = Math.floor(Math.random() * (title_arr.length));    
    let paths = 'pages/store/index?store_id=' + store_id + '&to=' + encodeURIComponent('/pages/cutprice/bargaindetail?store_id=' + store_id + '&share_id=' + share_id + '&sharerecord=cutPriceCard' + '&user_id=' + share_id +'&bnorid='+bnorid);
    return {
      title: title_arr[index],
      path: paths,
      imageUrl: 'https:' + that.data.share_url,
    }
  }
})